package net.kts.attraction.subway;

import java.util.ArrayList;
import java.util.List;


import net.kts.attraction.search.model.Address;
import net.kts.attraction.subway.adapter.SubwayAdapter;
import net.kts.attraction.subway.positon.SubwayPositionDaoSQLite;
import net.kts.attraction.subway.positon.model.SubwayPosition;
import net.kts.attraction.subway.smallpass.SmallSubwayStartActivity;
import net.kts.attraction.subway.smallpass.model.StationName;
import net.kts.attraction.subway.smallpass.sqlite.SubwayNameDaoSQLite;
import net.kts.define.SQLiteDatabaseStr;
import net.kts.location.MyLocationManager;
import net.kts.main.R;
import net.kts.setting.language.LanguageUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class SubwayListActivity extends Activity {

//	private LocationManager locationManager = null;
	private LocationListener locationListener = null;
	private boolean locationFlag = false;
	private int providerFlag = 1; //1 gps 2 network
	
	private SubwayPositionDaoSQLite positionDaoSQLite = null;
	private SubwayNameDaoSQLite subwayNameDaoSQLite = null;
	
	private OnItemClickListener onItemClickListener = null;
	private List<StationName> stationNameList = null;
	
	private Address address = null;
	
	private ProgressDialog progressDialog = null;
	
	private ListView listView = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.attraction_subway_ready_list);
		
		progressDialog = new ProgressDialog(this);//ProgressDialog.show(this, "Search Surround Subway", "Searching....");
		progressDialog.setMessage("Search Surround Subway..");
		progressDialog.show();
		
//		locationListenerInit();
		itemClickListenerInit();
		getIntentInit();
		
		this.listView = (ListView)findViewById(R.id.attraction_sbuway_ready_listview);
		this.listView.setOnItemClickListener(this.onItemClickListener);
		
		if(this.positionDaoSQLite != null) {
			this.positionDaoSQLite.close();
		}
		this.positionDaoSQLite = new SubwayPositionDaoSQLite(this, SQLiteDatabaseStr.dbFileName, null, 1);
		if(this.subwayNameDaoSQLite != null) {
			this.subwayNameDaoSQLite.close();
		}
		this.subwayNameDaoSQLite = new SubwayNameDaoSQLite(this, SQLiteDatabaseStr.dbFileName, null, 1);
		
//		this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//		
//		String bestProvider = this.locationManager.getBestProvider(BestProvider.getBestProviderCriteria(), true);
//		
//		this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 1, this.locationListener);
//		this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, this.locationListener);
	}
	
	private void getIntentInit() {
		 Intent intent = getIntent();
		 Bundle bundle = intent.getExtras();
		 this.address = (Address)bundle.get("address");
		
	}
	
	
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		if(this.locationListener == null) {
			this.locationListenerInit();
			MyLocationManager.addLocationListener(this.locationListener);
		}
		
		changeLocation(MyLocationManager.giveMeMyCurrentLocation());
		
//		if(this.locationManager == null) {
//			this.finish();
//		}
		
		
//		String bestProvider = this.locationManager.getBestProvider(BestProvider.getBestProviderCriteria(), true);
//		
//		this.locationManager.requestLocationUpdates(bestProvider, 0, 1, this.locationListener);
	}

	private void itemClickListenerInit() {
		// TODO Auto-generated method stub
		this.onItemClickListener = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> items, View v, int position,
					long id) {
				// TODO Auto-generated method stub
				
				StationName stationName = stationNameList.get(position);
				
				//Toast.makeText(getBaseContext(), stationName.getStationName() + ": " + String.valueOf(stationName.getSubwayPosition().getDistance()), Toast.LENGTH_SHORT).show();
				
				
				Intent intent = new Intent(getBaseContext(), SmallSubwayStartActivity.class);
				
				int startStatonCode = stationName.getStationCode();
				
				double latltude = Double.valueOf(address.getLatitude());
				double longitude = Double.valueOf(address.getLongitude());
				
				int targetStationCode = 0;
				
				Location location = new Location("target");
				location.setLatitude(latltude);
				location.setLongitude(longitude);
				
				double surround = 0.01;
				List<SubwayPosition> positionList = null;
				while(positionList == null ) {
					positionList = positionDaoSQLite.getlocationList(location, surround);
					surround += 0.01;
				}				
				
				SubwayPosition targetPosition = getNearPosition(location, positionList);
				
				if(targetPosition == null) {	
					Toast.makeText(getBaseContext(), "There is no destination around the metro", Toast.LENGTH_SHORT).show();
//					progressDialog.dismiss();
					finish();
					return;
				}
				
				Bundle bundle = new Bundle();
				bundle.putInt("startCode", startStatonCode);
				bundle.putInt("endCode", targetPosition.getStationCode());
				intent.putExtras(bundle);
				
				startActivity(intent);
				
				Log.d("kts", "stationCode : " +stationName.getStationCode() );
			}
		};
	}

	private void locationListenerInit() {
		
		this.locationListener = new LocationListener() {
			
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				// 
//				Toast.makeText(getBaseContext(), "New location latitude ["  +
//			    		lat + "] longitude [" + lng + "]", Toast.LENGTH_SHORT).show();
				changeLocation(location);
			}
		};
		
	}
	
	public void changeLocation(Location location) {
		//this.locationFlag = true;
		
		

		
		List<SubwayPosition> positionList = this.positionDaoSQLite.getlocationList(location, -1);
		StationName stationName = null;
		
		if(positionList == null) {
			
			Toast.makeText(this, "Not Found Surround Subway", Toast.LENGTH_SHORT).show();
			progressDialog.dismiss();
			finish();
			return;
		}
		
			
		String line = null;
		String walkTime = null;
		double distance = 0;
		//호占쏙옙
		// 占신몌옙
		// 占쏙옙占쏙옙
			
		if(positionList != null) {
			stationNameList = new ArrayList<StationName>();
			
			for(SubwayPosition position : positionList) {
				
				distance = location.distanceTo(position);
				position.setDistance(distance);
				
				stationName = this.subwayNameDaoSQLite.selectStationName(position.getStationCode(), LanguageUtil.getCurrentLanguage());
				stationName.setSubwayPosition(position);
				line = this.getLine(stationName);
				walkTime = this.getWalkTime(position.getDistance());
				
				if(stationName.getStationCodeList() != null) {
					
					for(int stationCode : stationName.getStationCodeList()) {
						if(stationCode == 44444) {
							continue;
						}
						
						try {
							StationName newName = (StationName)stationName.clone();
							
							newName.setLineNum(this.subwayNameDaoSQLite.selectLineNum(stationCode));
							
							stationNameList.add(newName);
						} catch (CloneNotSupportedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}
					
					continue;
				}
			
				
				stationNameList.add(stationName);
			}			
			
		}
		else {
			Toast.makeText(getBaseContext(), "Not Found Subway", Toast.LENGTH_SHORT).show();
		}
		
		SubwayAdapter subwayAdapter = new SubwayAdapter(this, R.layout.attraction_subway_ready_row, stationNameList);
		this.listView.setAdapter(subwayAdapter);
		
		this.progressDialog.dismiss();

	}
	
	// 占싯삼옙占쏙옙占�100占쏙옙占쏙옙 占싫는듸옙 100占쏙옙占쏙옙占쏙옙 占실몌옙占쌕곤옙 占싼댐옙 ;; 占쏙옙占쏙옙 占싫댐옙 占쏙옙占쏙옙占�占시쇽옙 4km占싱띰옙.. 占십쇽옙 1.11m ;;
	private String getWalkTime(double distance) {
		// TODO Auto-generated method stub
		
		int dis = (int)distance;
		
		int minute = dis/ 60;
		
		return String.valueOf(minute + 1);
	}

	



	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
//		this.locationManager.removeUpdates(this.locationListener);
//		this.locationManager.removeUpdates(this.locationListener);
	}

	private String getLine(StationName stationName) {
		
		String line = null;
		
		if(stationName.getStationCodeList() == null) {
			return String.valueOf(stationName.getLineNum());
		}
		
		line = "";
		
		for(int indexI = 0 ; indexI < stationName.getStationCodeList().size(); ++ indexI) {
			if(indexI != 0) {
				line += ", ";
			}
			
			line += String.valueOf(stationName.getStationCodeList().get(indexI));
			
		}
		
		return line;
	}
	
	
	private SubwayPosition getNearPosition(Location location, List<SubwayPosition> positionList) {
		
		SubwayPosition position = null;
		SubwayPosition temp = null;
		double distance = 0;
		
		if(positionList == null) {
			return position;
		}
		
		if(positionList.size() == 1) {
			return positionList.get(0);
		}
		
		for(int indexI = 0 ; indexI < positionList.size() ; ++indexI) {
			temp = positionList.get(indexI);
			distance = location.distanceTo(temp);
			temp.setDistance(distance);
			
			
			if(position == null) {
				position = temp;
			}
			else {
				if(position.getDistance() > temp.getDistance()) {
					position = temp;
				}
			}
			
		}
		
 		
		return position;
		
	}

}
